import os
import requests
from models.basemodel import BaseModel
from openai import OpenAI
from typing import List, Optional, Dict, Tuple
from concurrent.futures import ThreadPoolExecutor

class DeepSeekModel(BaseModel):
    platform_name = "DeepSeek"
    def __init__(self):
        super().__init__()
        self.api_key = "sk-6af5b58167f245888c02d7515ab83e82"
        self.uplaod_url = "https://api.deepseek.com/upload"
        self.chat_url = "https://api.deepseek.com"
        self.client = OpenAI(api_key=self.api_key, base_url=self.chat_url)
        self.model_name = "deepseek-chat"

    def setModelName(self, model_name):
        self.model_name = model_name
        
    def chat(self, messages:List[Dict[str, str]]):
        response = self.client.chat.completions.create(
            model=self.model_name,
            messages=messages,
            stream=True
        )

        for chunk in response:
            if chunk.choices[0].delta.content:
                chunk_content = chunk.choices[0].delta.content
                yield chunk_content
    
    def _upload_file(self, file_path: str) -> Dict:
        headers = {
            "Authorization": f"Bearer {self.api_key}" 
        }

        try:
            if not os.path.exists(file_path):
                return {"status": "error", "message": "File not found"}

            with open(file_path, "rb") as file:
                files = {"file": (os.path.basename(file_path), file)}
                response = self.session.post( 
                    self.upload_url,  
                    headers=headers,
                    files=files,
                    timeout=30 
                )
                response.raise_for_status()
                return response.json()

        except requests.exceptions.RequestException as e:
            error_details: Optional[str] = None
            if e.response is not None:
                try:
                    error_details = e.response.text
                except AttributeError:
                    pass
            return {
                "status": "error",
                "message": f"Upload failed: {str(e)}",
                "details": error_details
            }

    def upload_files(self, file_list: List[str]) -> List[Dict]:
        with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
            results = list(executor.map(self._upload_file, file_list)) 
        return results                  
            
    def name(self):
        return self.model_name
    
    def deleteChat(self) ->bool:
        return True
    
    def getModelList(self) ->List[Tuple[str, str]]:
        return []